<template>
  <div class="blood-sugar-container">
    <div class="table-operations">
      <a-card title="血糖记录筛选" :bordered="false">
        <a-form layout="horizontal" :model="searchForm">
          <a-row :gutter="24">
            <a-col :span="6">
              <a-form-item label="用户ID" name="userId">
                <a-input-number v-model:value="searchForm.userId" style="width: 100%" placeholder="请输入用户ID" />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="开始日期" name="startDate">
                <a-date-picker 
                  v-model:value="searchForm.startDate" 
                  style="width: 100%" 
                  :locale="zhCN"
                  format="YYYY-MM-DD"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="结束日期" name="endDate">
                <a-date-picker 
                  v-model:value="searchForm.endDate" 
                  style="width: 100%" 
                  :locale="zhCN"
                  format="YYYY-MM-DD"
                />
              </a-form-item>
            </a-col>
            <a-col :span="6">
              <a-form-item label="测量类型" name="measureType">
                <a-select v-model:value="searchForm.measureType" placeholder="请选择" allow-clear>
                  <a-select-option :value="1">空腹</a-select-option>
                  <a-select-option :value="2">餐后2小时</a-select-option>
                  <a-select-option :value="3">随机</a-select-option>
                </a-select>
              </a-form-item>
            </a-col>
          </a-row>
          <a-row>
            <a-col :span="24" style="text-align: right">
              <a-button type="primary" @click="onSearch">
                <search-outlined />
                查询
              </a-button>
              <a-button style="margin-left: 8px" @click="onReset">
                <reload-outlined />
                重置
              </a-button>
            </a-col>
          </a-row>
        </a-form>
      </a-card>
    </div>

    <a-card title="血糖记录列表" :bordered="false" style="margin-top: 16px">
      <a-table
        :columns="columns"
        :data-source="recordList"
        :pagination="pagination"
        :loading="loading"
        @change="handleTableChange"
        row-key="id"
        size="middle"
        bordered
      >
        <template #bodyCell="{ column, text, record }">
          <template v-if="column.dataIndex === 'value'">
            <span :style="{ color: getValueColor(record) }">{{ text }}</span>
          </template>
          
          <template v-if="column.dataIndex === 'measureTypeName'">
            {{ text }}
          </template>
          
          <template v-if="column.dataIndex === 'status'">
            <a-tag :color="getStatusTagColor(record.status)">
              {{ record.statusText }}
            </a-tag>
          </template>
          
          <template v-if="column.dataIndex === 'measureTime'">
            {{ formatDateTime(text) }}
          </template>
          
          <template v-if="column.dataIndex === 'action'">
            <a-space>
              <a @click="viewDetails(record)">详情</a>
              <a-divider type="vertical" />
              <a-popconfirm
                title="确定要删除这条记录吗？"
                ok-text="确定"
                cancel-text="取消"
                @confirm="deleteRecord(record)"
              >
                <a class="danger-text">删除</a>
              </a-popconfirm>
            </a-space>
          </template>
        </template>
      </a-table>
    </a-card>
  </div>
</template>

<script setup>
import { ref, reactive, onMounted } from 'vue';
import { useRouter } from 'vue-router';
import { message } from 'ant-design-vue';
import { SearchOutlined, ReloadOutlined } from '@ant-design/icons-vue';
import axios from 'axios';
import zhCN from 'ant-design-vue/es/date-picker/locale/zh_CN';

const router = useRouter();
const loading = ref(false);
const recordList = ref([]);

// 表格列定义
const columns = [
  {
    title: '记录ID',
    dataIndex: 'id',
    width: 80
  },
  {
    title: '用户ID',
    dataIndex: 'userId',
    width: 80
  },
  {
    title: '用户昵称',
    dataIndex: 'nickname',
    ellipsis: true
  },
  {
    title: '血糖值',
    dataIndex: 'value',
    sorter: true,
    width: 100
  },
  {
    title: '测量类型',
    dataIndex: 'measureTypeName',
    width: 120
  },
  {
    title: '状态',
    dataIndex: 'status',
    width: 100
  },
  {
    title: '测量时间',
    dataIndex: 'measureTime',
    sorter: true,
    width: 180
  },
  {
    title: '备注',
    dataIndex: 'remark',
    ellipsis: true
  },
  {
    title: '操作',
    dataIndex: 'action',
    width: 150,
    fixed: 'right'
  }
];

// 搜索表单数据
const searchForm = reactive({
  userId: undefined,
  startDate: null,
  endDate: null,
  measureType: undefined,
  page: 1,
  size: 10
});

// 分页配置
const pagination = reactive({
  current: 1,
  pageSize: 10,
  total: 0,
  showSizeChanger: true,
  showQuickJumper: true,
  showTotal: (total) => `共 ${total} 条记录`
});

// 获取血糖记录列表
const fetchRecordList = async () => {
  try {
    loading.value = true;
    
    // 处理日期参数
    const params = { ...searchForm };
    if (params.startDate) {
      params.startDate = formatDate(params.startDate);
    }
    if (params.endDate) {
      params.endDate = formatDate(params.endDate);
    }
    
    const response = await axios.get('/admin/blood-sugar/list', { 
      params: {
        ...params,
        page: pagination.current,
        size: pagination.pageSize
      }
    });
    
    if (response.data.code === 0) {
      recordList.value = response.data.data.records;
      pagination.total = response.data.data.total;
    } else {
      message.error(response.data.message || '获取血糖记录失败');
    }
  } catch (error) {
    console.error('获取血糖记录错误', error);
    message.error('获取血糖记录失败');
  } finally {
    loading.value = false;
  }
};

// 搜索
const onSearch = () => {
  pagination.current = 1;
  fetchRecordList();
};

// 重置
const onReset = () => {
  // 重置表单
  Object.keys(searchForm).forEach(key => {
    searchForm[key] = undefined;
  });
  searchForm.page = 1;
  searchForm.size = 10;
  
  // 重置分页
  pagination.current = 1;
  
  // 重新加载数据
  fetchRecordList();
};

// 表格变化处理
const handleTableChange = (pag, filters, sorter) => {
  pagination.current = pag.current;
  pagination.pageSize = pag.pageSize;
  
  // 处理排序
  if (sorter.field && sorter.order) {
    const orderMap = {
      ascend: 'asc',
      descend: 'desc'
    };
    searchForm.sort = `${sorter.field},${orderMap[sorter.order]}`;
  } else {
    searchForm.sort = undefined;
  }
  
  fetchRecordList();
};

// 查看详情
const viewDetails = (record) => {
  router.push(`/blood-sugar-detail/${record.id}`);
};

// 删除记录
const deleteRecord = async (record) => {
  try {
    const response = await axios.delete(`/admin/blood-sugar/${record.id}`);
    
    if (response.data.code === 0) {
      message.success('删除成功');
      // 刷新列表
      fetchRecordList();
    } else {
      message.error(response.data.message || '删除失败');
    }
  } catch (error) {
    console.error('删除血糖记录错误', error);
    message.error('删除失败');
  }
};

// 获取血糖值状态颜色
const getValueColor = (record) => {
  if (!record.status) return '';
  
  switch (record.status) {
    case 1: return '#52c41a'; // 正常
    case 2: return '#faad14'; // 偏低
    case 3: return '#f5222d'; // 偏高
    default: return '';
  }
};

// 获取状态标签颜色
const getStatusTagColor = (status) => {
  if (!status) return '';
  
  switch (status) {
    case 1: return 'green'; // 正常
    case 2: return 'orange'; // 偏低
    case 3: return 'red'; // 偏高
    default: return '';
  }
};

// 格式化日期 YYYY-MM-DD
const formatDate = (date) => {
  if (!date) return '';
  if (typeof date === 'string') return date;
  
  const year = date.getFullYear();
  const month = String(date.getMonth() + 1).padStart(2, '0');
  const day = String(date.getDate()).padStart(2, '0');
  
  return `${year}-${month}-${day}`;
};

// 格式化日期和时间
const formatDateTime = (dateString) => {
  if (!dateString) return '';
  const date = new Date(dateString);
  return date.toLocaleString('zh-CN', {
    year: 'numeric',
    month: '2-digit',
    day: '2-digit',
    hour: '2-digit',
    minute: '2-digit',
    second: '2-digit'
  });
};

onMounted(() => {
  fetchRecordList();
});
</script>

<style scoped>
.blood-sugar-container {
  padding: 0;
}

.table-operations {
  margin-bottom: 16px;
}

.danger-text {
  color: #ff4d4f;
}
</style> 